package com.neuralnoise.linkedin;

import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.configuration.ConfigurationException;

public class ParseArgs {

	private LinkedInProperties properties;
	
	public ParseArgs(String[] args) throws ConfigurationException {
		
		Options options = new Options();
		
		options.addOption("h", "help", false, "Help message");
		options.addOption("p", "properties", true, "Configuration file (t.properties)");
		options.addOption("s", "startUser", true, "Initial User node for Crawling (BFS)");
		options.addOption("m", "millis", true, "Milliseconds between each User crawl");
		
		CommandLineParser parser = new BasicParser();
		
		CommandLine cmdLine = null;
		try {
			cmdLine = parser.parse(options, args);
		} catch (ParseException e) {
			System.out.println(e.getMessage());
			showHelp(options);
		}

		if (cmdLine.hasOption("h")) {
        	showHelp(options);
        }

		String properties = parameterString(cmdLine, 'p', "properties");
		this.properties = (properties == null
				? new LinkedInProperties() : new LinkedInProperties(properties));
		
		String startUser = parameterString(cmdLine, 's', "startUser");
		if (startUser != null) {
			this.properties.setStartUser(startUser);
		}

		Long millis = parameterLong(cmdLine, 'm', "millis");
		if (millis != null) {
			this.properties.setMillis(millis);
		}
	}
	
	public static String parameterString(CommandLine cmdLine, char shortParameter, String longParameter) {
		String ret = null;
		if (cmdLine.hasOption(shortParameter)) {
			ret = cmdLine.getOptionValue(longParameter);
		}
		return ret;
	}
	
	public static Long parameterLong(CommandLine cmdLine, char shortParameter, String longParameter) {
		Long ret = null;
		if (cmdLine.hasOption(shortParameter)) {
			ret = Long.valueOf(cmdLine.getOptionValue(longParameter));
		}
		return ret;
	}
	
	private static void showHelp(Options options) {
		HelpFormatter hf = new HelpFormatter();
		hf.setWidth(128);
		hf.printHelp(LinkedInCrawler.class.getCanonicalName(), options);
		System.exit(-1);
	}

	public LinkedInProperties getProperties() {
		return properties;
	}

	public void setProperties(LinkedInProperties properties) {
		this.properties = properties;
	}
	
}
